var upParaId;
var id;
var noteId = jQuery('#noteId').val();
var name;
var memo;
var serverData = {};
var serverTable;
var serverModelData = {};
var serverModelTable;
var servernotData = {};
var servernotTable;
var pointType =  $('input:radio[name="isReceived"]:checked').val();
jQuery(document).ready(function () {
	serverData.key = "";
	pointType=$('input:radio[name="isReceived"]:checked').val();
	serverData.pointType = pointType;
	serverData.Type = "引入";
	serverData.id = "";
	serverTable = jQuery('#scadaBaseTable').DataTable({
        "serverSide": true,
        "ordering": false,
        "ajax": {
            "dataType": "json",
            "type": "get",
            "cache": false,
            "url":window.rootPath+ '/ui/ScadaModelBaseInfo/getpageScadaBase',
            "data": function (d) {
                return $.extend({}, d, serverData);
            }
        },
        columns: [
				{
					data: null
				},
				{
				    data: null,
				    defaultContent: "",
				    render: function (data, type, full, meta) {
				    	var id=data.id
				    	var operate ='<input type="checkbox" class="checkchildCruxDate">';
				    	return operate;
				    }   
				},
				{
					data: 'name'
				},
				{
					data: 'scadaRtuBaseInfoName'
				},
				{
				    data: 'alias'
				},
				{
					data: 'pointType',//0实点，1虚点
					render: function (data, type, full, meta) {
				      	var dOut;
				      	 if(data=='0'){
				      		dOut = '<td class="center" >实点</td>';
				      	}
				      	else if(data=='1'){
				      		dOut = '<td class="center" >虚点</td>';
				      	}
				    	return dOut;
				      }
				},
				{
				    data: 'dataType',//0 模拟量  1 开关量
				    render: function (data, type, full, meta) {
				      	var dOut;
				      	 if(data=='0'){
				      		dOut = '<td class="center" >模拟量</td>';
				      	}
				      	else if(data=='1'){
				      		dOut = '<td class="center" >开关量</td>';
				      	}
				    	return dOut;
				      }
				},
				{
					data: 'unit'
				},
				{
					data: 'upperLimit'
				},
				{
					data: 'lowLimit'
				},
				{
					data: 'dataField'
				},
				{
					data: 'user.name'
				},
				{
					data: 'createTime',
				    render: function (data, type, full, meta) {
				        if (data)
				            return moment(data).format('YYYY/MM/DD');
				        else
				            return '';
				    }
				},
				{
					data: 'memo'
				}
				],
        "drawCallback": function (oSettings) {
            var k = 0;
            var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

            for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                k++;
            }
        }
    });
	servernotData.key = "";
	servernotData.pointType = "";
	servernotData.Type = "未引入";
	servernotData.id = "";
	servernotTable = jQuery('#scadaBasenotTable').DataTable({
        "serverSide": true,
        "ordering": false,
        "ajax": {
            "dataType": "json",
            "type": "get",
            "cache": false,
            "url":window.rootPath+ '/ui/ScadaModelBaseInfo/getpageScadaBase',
            "data": function (d) {
                return $.extend({}, d, servernotData);
            }
        },
        columns: [
				{
					data: null
				},
				{
				    data: null,
				    defaultContent: "",
				    render: function (data, type, full, meta) {
				    	var id=data.id
				    	var operate ='<input type="checkbox" class="checkchildCruxDate">';
				    	return operate;
				    }   
				},
				{
					data: 'name'
				},
				{
					data: 'scadaRtuBaseInfoName'
				},
				{
				    data: 'alias'
				},
				{
					data: 'pointType',//0实点，1虚点
					render: function (data, type, full, meta) {
				      	var dOut;
				      	 if(data=='0'){
				      		dOut = '<td class="center" >实点</td>';
				      	}
				      	else if(data=='1'){
				      		dOut = '<td class="center" >虚点</td>';
				      	}
				    	return dOut;
				      }
				},
				{
				    data: 'dataType',//0 模拟量  1 开关量
				    render: function (data, type, full, meta) {
				      	var dOut;
				      	 if(data=='0'){
				      		dOut = '<td class="center" >模拟量</td>';
				      	}
				      	else if(data=='1'){
				      		dOut = '<td class="center" >开关量</td>';
				      	}
				    	return dOut;
				      }
				},
				{
					data: 'unit'
				},
				{
					data: 'upperLimit'
				},
				{
					data: 'lowLimit'
				},
				{
					data: 'dataField'
				},
				{
					data: 'user.name'
				},
				{
					data: 'createTime',
				    render: function (data, type, full, meta) {
				        if (data)
				            return moment(data).format('YYYY/MM/DD');
				        else
				            return '';
				    }
				},
				{
					data: 'memo'
				}
				],
        "drawCallback": function (oSettings) {
            var k = 0;
            var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

            for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                k++;
            }
        }
    });
	
	serverModelTable = jQuery('#scadaModelTable').DataTable({
        "serverSide": true,
        "ordering": false,
        "ajax": {
            "dataType": "json",
            "type": "get",
            "cache": false,
            "url":window.rootPath+ '/ui/ScadaModelBaseInfo/getpage',
            "data": function (d) {
                return $.extend({}, d, serverModelData);
            }
        },
        columns: [
            {
            	data: null
            },
            {
	            data: null,
	            defaultContent: "",
	            render: function (data, type, full, meta) {
	            	var id=data.id
	            	var operate ='<input type="checkbox" class="checkchildContract">';
	            	return operate;
	            }   
            },
            {
                data: 'modelName'
            },
            {
            	data: 'user.name'
            },
            {
                data: 'createTime',
                render: function (data, type, full, meta) {
                    if (data)
                        return moment(data).format('YYYY/MM/DD');
                    else
                        return '';
                }
            },
            {
                data: 'memo'
            }
            ],
        "drawCallback": function (oSettings) {
            var k = 0;
            var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

            for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                k++;
            }
        }
    });
	//模型查询
	jQuery('.searchModelBtn').on('click', function () {
		serverModelData.key = jQuery('#keyword2').val();
		serverModelTable.draw();
	});
	jQuery('.resetModelBtn').on('click', function () {
		jQuery('#keyword2').val("");
		serverModelData.key = "";
		serverModelTable.draw();
	});
	
	//查询按钮
	jQuery('.searchBtn').on('click', function() {
		serverData.key = jQuery("#keyword").val();
		pointType=$('input:radio[name="isReceived"]:checked').val();
		serverData.pointType = pointType;
		serverData.Type = "引入";
		serverData.id = id;
		serverTable.draw();
	});
	// 撤消查询
	jQuery('.resetBtn').on('click', function() {
		jQuery('#keyword').val('');
		serverData.key = "";
		pointType=$('input:radio[name="isReceived"]:checked').val();
		serverData.pointType = pointType;
		serverData.Type = "引入";
		serverData.id = id;
		serverTable.draw();
	});
	
	//获取选中状态
	$(function(){
		  $(":radio").click(function(){
			  serverData.key = jQuery('#keyword').val();
			  pointType=$('input:radio[name="isReceived"]:checked').val();
			  serverData.pointType = pointType;
			  serverData.Type = "引入";
			  serverData.id = id;
			  serverTable.draw();
		  });
	});
	
	//查询未引入按钮
	jQuery('.searchnotBtn').on('click', function() {
		servernotData.key = jQuery("#keyword1").val();
		servernotData.pointType = "";
		servernotData.Type = "未引入";
		servernotData.id = "";
		servernotTable.draw();
	});
	// 撤消查询
	jQuery('.resetnotBtn').on('click', function() {
		jQuery('#keyword1').val('');
		servernotData.key = "";
		servernotData.pointType = "";
		servernotData.Type = "未引入";
		servernotData.id = "";
		servernotTable.draw();
	});
	
	//主节点
	jQuery('.addRootNodeBtn').on('click', function () {
		if(jQuery('#noteId').val()!=""){
			alert("已存在主节点，不能添加主节点！");
		}else{
			jQuery('#upParaId').val('');
			jQuery('#RootNodeid').val('');
			jQuery('#RootNodecreateTime').val('');
			jQuery('#RootNodename').val('');
			jQuery('#RootNodememo').val('');
			jQuery('#divideRootNodeModal').modal('show');
		}
	});
	//子节点
	jQuery('.addChildNodeBtn').on('click', function () {
//		var treeObj = $.fn.zTree.getZTreeObj("deviceTree");
//		var nodes = treeObj.getCheckedNodes(true);
		if(id != undefined && id !=""){
			jQuery('#upParaId').val(id);
			jQuery('#RootNodeid').val('');
			jQuery('#RootNodecreateTime').val('');
			jQuery('#RootNodename').val('');
			jQuery('#RootNodememo').val('');
			jQuery('#divideRootNodeModal').modal('show');
		}else{
			alert("请选择节点！");
		}
	});
	//编辑节点
	jQuery('.editNodeBtn').on('click', function () {
//		var treeObj = $.fn.zTree.getZTreeObj("deviceTree");
//		var nodes = treeObj.getCheckedNodes(true);
		if(id != undefined && id !=""){
			jQuery('#upParaId').val('');
			jQuery('#RootNodeid').val(id);
			jQuery('#RootNodecreateTime').val('');
			jQuery('#RootNodename').val(name);
			jQuery('#RootNodememo').val(memo);
			jQuery('#divideRootNodeModal').modal('show');
		}else{
			alert("请选择节点！");
		}
	});
	//保存节点
	jQuery('.saveRootNodeBtn').on('click', function () {
		upParaId = jQuery('#upParaId').val();
		var RootNodeid = jQuery('#RootNodeid').val();
		var createTime = jQuery('#RootNodecreateTime').val();
		var name = jQuery('#RootNodename').val();
		var memo = jQuery('#RootNodememo').val();
		var d;
		if(id == null || id == ""){
			d = {
					"upParaId" : upParaId,
					"createTime" : new Date(),
					"modelName" : name,
					"memo" : memo,
			};
		}else {
			d = {
					"upParaId" : upParaId,
					"id" : RootNodeid,
					"createTime" : createTime,
					"modelName" : name,
					"memo" : memo,
			};
		}
		var url=window.rootPath+'/ui/ScadaModelBaseInfo/saveScadaModelBaseInfo';
        jQuery.ajax({
            url:encodeURI(url),
            type:'post',
            data:JSON.stringify(d),
            dataType:'json',
            contentType:'application/json;charset=utf-8',
            success: function (data) {
            	if(data.noteId!=null){
            		jQuery('#noteId').val(data.noteId);
            		noteId = data.noteId;
            	}
            	jQuery('#divideRootNodeModal').modal('hide');
            	//jQuery('#upParaId').val('');
        		jQuery('#RootNodeid').val('');
        		jQuery('#RootNodecreateTime').val('');
        		jQuery('#RootNodename').val('');
        		jQuery('#RootNodememo').val('');
        		jQuery('#divideRootNodeModal').modal('hide');
        		jQuery('#ztreef').val('');
        		tree(noteId);
        		id="";
        		name="";
        		jQuery('#name').val("");
        		memo="";
        		serverTable.draw();
				servernotTable.draw();
        		//serverTable.draw();
            }
        });
	});
	
	
	
//////初始化设备的树结构//////////
	var modalSetting = {
		edit : {
			enable : true,
			showRemoveBtn : false,
			showRenameBtn : false
		},
		data : {
			simpleData : {
				enable : true,
				idKey : "id",
				pIdKey : "parentId",
				rootParentId : 0
			},
			key : {
				name : "name",
				memo : "memo"
			}
		},
		check : {
			enable : true,
			chkStyle : "radio"

		},
		view : {
			showLine : true
		},
		callback:{
			onCheck: showNode
		}
	};
	
	var urltree =window.rootPath+"/ui/ScadaModelBaseInfo/getTree?id=" + noteId;
	var firstNode = [];
	jQuery.ajax({
		url: encodeURI(urltree),
		cache: false,
		type: "get",
		dataType: "json",
		contentType: "application/json;charset=utf-8",//解决返回数据中的中文乱码问题
		success: function (data) {
			if (data.deviceType.length > 0) {
				for (var i = 0; i < data.deviceType.length; i++) {
					  firstNode.push(data.deviceType[i]);
				}
			}
			$.fn.zTree.init($("#deviceTree"), modalSetting, firstNode);
		}
	});
	
	var tree = function(noteId){
		var urltree =window.rootPath+"/ui/ScadaModelBaseInfo/getTree?id=" + noteId;
		var firstNode = [];
		jQuery.ajax({
			url: encodeURI(urltree),
			cache: false,
			type: "get",
			dataType: "json",
			contentType: "application/json;charset=utf-8",//解决返回数据中的中文乱码问题
			success: function (data) {
				if (data.deviceType.length > 0) {
					for (var i = 0; i < data.deviceType.length; i++) {
						  firstNode.push(data.deviceType[i]);
					}
				}
				$.fn.zTree.init($("#deviceTree"), modalSetting, firstNode);
			}
		});
	}
	
////////点击显示节点相关的方案///////
	function showNode(event, treeId, treeNode){
		id=treeNode.id;
		name = treeNode.name;
		jQuery('#name').val(name);
		memo = treeNode.memo;
		serverData.id=id;
		serverTable.draw(true);
	}
	//引入点位弹窗
	jQuery('.addBtn').on('click', function () {
		if(id != undefined && id !=""){
			jQuery('#RootNodeNotid').val(id);
			servernotTable.draw();
			jQuery('#divideRootNodeNotModal').modal('show');
		}else{
			alert("请选择节点！");
		}
	});
	//点位引入
	jQuery('.addRootNodeNotBtn').on('click', function () {
		var modelId = jQuery('#RootNodeNotid').val();
		var selects = getSelect("#scadaBasenotTable", 1);
		if(modelId==""){
			alert("请选择节点！");
		}else if(selects.length<1){
			alert("请选择点位！");
		}else if(selects.length>0){
			var pointIds = "";
			for (var i = 0; i < selects.length; i++) {
				pointIds += selects[i].id + ",";
			}
			pointIds = pointIds.substring(0, pointIds.length-1);
			var urlpointId = window.rootPath+"/ui/ScadaModelBaseInfo/savescadaModelPointRelation?modelId="+modelId+"&pointIds="+pointIds;
			jQuery.ajax({
				url: encodeURI(urlpointId),
				cache: false,
				type: "get",
				dataType: "json",
				contentType: "application/json;charset=utf-8",//解决返回数据中的中文乱码问题
				success: function (data) {
					jQuery('#ModelNodeNotid').val('');
					jQuery('#divideRootNodeNotModal').modal('hide');
					serverTable.draw();
					servernotTable.draw();
				}
			});
		}
	});
	//点位删除
	jQuery('.delBtn').on('click', function () {
		var selects = getSelect("#scadaBaseTable", 1);
		if(selects.length<1){
			alert("请选择点位！");
		}else if(selects.length>0 && id != undefined && id !=""){
			var pointIds = "";
			for (var i = 0; i < selects.length; i++) {
				pointIds += selects[i].id + ",";
			}
			pointIds = pointIds.substring(0, pointIds.length-1);
			$.springLemonDialog({
		         content: '确认删除'+selects.length+'条点位？',// 确认文本
		         clickButton: function (sender, modal, index) {// 按钮事件处理
		        	 if (index == 0) {
		        		 var url=window.rootPath+"/ui/ScadaModelBaseInfo/deletePoint"+"?pointIds="+ pointIds;
	                        jQuery.ajax({
	                            url:encodeURI(url),
	                            cache:false,
	                            type : "get",
	                            dataType:"json",
	                            success:function(data){
	                                serverTable.draw();
	                                servernotTable.draw();
	                            }
	                        });
		        	 }
		             $(this).closeDialog(modal);
		         }
		       }); 
		}else{
			alert("请选择节点！");
		}
	});
	//模型引入弹窗
	jQuery('.addModelBtn').on('click', function () {
		if(id != undefined && id !=""){
			jQuery('#ModelNodeNotid').val(id);
			servernotTable.draw();
			jQuery('#divideModelNodeNotModal').modal('show');
		}else{
			alert("请选择节点！");
		}
	});
	//模型引入
	jQuery('.addModelNodeNotBtn').on('click', function () {
		var modelId = jQuery('#ModelNodeNotid').val();
		var noteId1 = jQuery('#noteId').val();
		var selects = getSelect("#scadaModelTable", 1);
		if(modelId==""){
			alert("请选择节点！");
		}else if(selects.length<1){
			alert("请选择引入模型！");
		}else if(selects.length>1){
			alert("只能引入一个模型！");
		}else if(selects.length==1){
			var pointId = selects[0].id;
			if(pointId == noteId){
				alert("不能引入自己的根节点！");
			}else {
				var urlmodelId = window.rootPath+"/ui/ScadaModelBaseInfo/savescadaModelPoint?modelId="+modelId+"&pointId="+pointId;
				jQuery.ajax({
					url: encodeURI(urlmodelId),
					cache: false,
					type: "get",
					dataType: "json",
					contentType: "application/json;charset=utf-8",//解决返回数据中的中文乱码问题
					success: function (data) {
						if(data.code==0){
							jQuery('#RootNodeNotid').val('');
							jQuery('#divideModelNodeNotModal').modal('hide');
							tree(noteId1);
							id="";
			        		name="";
			        		jQuery('#name').val("");
			        		memo="";
						}
					}
				});
			}
		}
	});
	//删除节点
	jQuery('.delNodeBtn').on('click', function () {
		//var id = getSelect("#scadaBaseTable", 1);
		if(id != undefined && id !=""){
			$.springLemonDialog({
				content: '确认删除此节点？',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					if (index == 0) {
						var url=window.rootPath+"/ui/ScadaModelBaseInfo/deleteNote"+"?id="+ id;
						jQuery.ajax({
							url:encodeURI(url),
							cache:false,
							type : "get",
							dataType:"json",
							success:function(data){
								tree(noteId);
								id="";
				        		name="";
				        		jQuery('#name').val("");
				        		memo="";
								serverData.id="";
								serverTable.draw();
								servernotTable.draw();
							}
						});
					}
					$(this).closeDialog(modal);
				}
			}); 
		}else{
			alert("请选择节点！");
		}
	});
});

